package com.ponhu.ea2.stockcenter.provider.service.biz.stockwarehouse;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.ponhu.ea2.stockcenter.dto.WMSEventInfoDTO;
import com.ponhu.ea2.stockcenter.enums.ExchangeActionTypeEnum;
import com.ponhu.ea2.stockcenter.provider.entity.StockInventoryDocOccupy;
import com.ponhu.ea2.stockcenter.provider.support.exception.StockRuntimeException;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.ponhu.ea2.stockcenter.enums.ExchangeActionTypeEnum.TRANSFER_OUT;
import static com.ponhu.ea2.stockcenter.enums.ResponseCodeEnum.STOCK_SALES_EXCEPTION_900305;

/**
 * 调拨出库
 */
@Component
public class TransferOutHandler extends AbsCoreHandler {

    public TransferOutHandler() {
        inOccupy = false;
        operateWarehouse = false; // 当前操作仓库是 outWarehouse
        whActionTypeArr = new ExchangeActionTypeEnum[]{TRANSFER_OUT};
    }

    @Override
    protected void absHandle(WMSEventInfoDTO eventInfoDTO) {

        // 调拨出库库存校验
        transferOutStockCheck(eventInfoDTO);

        // 仓库库存变动数据库操作
        stockWarehouseHandle(eventInfoDTO);

        // 调拨出库的特有操作
        transferOutHandle(eventInfoDTO);
    }

    /**
     * 调拨出库库存校验
     */
    protected void transferOutStockCheck(WMSEventInfoDTO eventInfoDTO) {

        // 校验出库货品是否存在当前仓库
        absUtilHandler.hasOperateInventory(eventInfoDTO);

        // 货品调拨申请锁定库存数量必须 >= 调拨出库的货品数量
        StringBuffer msg = new StringBuffer();
        absUtilHandler.whStockAllMacth(stock -> {
            Integer inventoryQuantity = inventoryLocal.get().get(stock.getInventoryCode());
            boolean macth = stock.getLockedStockNum() >= inventoryQuantity;
            if (BooleanUtils.isNotTrue(macth))
                msg.append(String.format(" 货品编码-%s:{调拨占用库存数(%s) >= 调拨请求库存数(%s)}校验失败；",
                        stock.getInventoryCode(), stock.getLockedStockNum(), inventoryQuantity));
            return macth;
        }, msg);
    }

    /**
     * 调拨出库的特有操作
     */
    private void transferOutHandle(WMSEventInfoDTO eventInfoDTO) {

        // 判断调拨申请是发生在可售仓到不可售仓之间
        if (!(eventInfoDTO.getOutWarehouseIsSale() && !eventInfoDTO.getInWarehouseIsSale())) return;

        // 当前调拨出库有关联业务单号
        if (StringUtils.isBlank(eventInfoDTO.getDocNo())) return;

        // 当前调拨申请或出库请求无销售侧单据占用
        List<StockInventoryDocOccupy> occupyList = stockInventoryDocOccupyService
                .getPlacedDocRecordList(eventInfoDTO.getDocNo());
        if (CollectionUtils.isEmpty(occupyList)) return;

        // 更新销售侧单据占用表状态
        if (!stockInventoryDocOccupyService.changeDocRecordToTransferAppliedAndOuted(
                eventInfoDTO.getDocNo(), eventInfoDTO.getActionType(), saleEventLocal.get())) {
            throw new StockRuntimeException(STOCK_SALES_EXCEPTION_900305);
        }
    }

}
